import cv2
import numpy as np
import time

'''# preload templates
list_templates = []
for k in range(10):
    img0 = cv2.imread("./templatesDir/"+str(k)+".jpg")
    list_templates.append(img0.astype(int))'''


def matchTemplate(target, template):
    w = 16#17
    h = 24#23
    min_dist = 99999
    kernel = np.ones((3,3), np.uint8)
    for dx in range(-1,2):
        for dy in range(-1, 2):
            imagea = target[1+dy:h-1+dy, 1+dx:w-1+dx]
            imageb = template[1+dy:h-1+dy, 1+dx:w-1+dx]
            diffimg = abs(imagea - imageb).astype(np.uint8)
            resizeimg = cv2.resize(diffimg, (w*2, h*2))
            erodeimg = cv2.erode(resizeimg, kernel, iterations=1)
            dist = erodeimg.sum()
            if dist < min_dist:
                min_dist = dist
                #cv2.imwrite(name, erodeimg)
    return min_dist


def matchTemplates(img, list_templates):
    h = img.shape[0]
    w = img.shape[1]
    img = img.astype(int)
    min_val = 999999
    min_index = 0
    for k in range(10):
        #sum = 0
        dist = matchTemplate(img, list_templates[k])
        if dist < min_val:
            min_val = dist
            min_index = k
    return min_index


def preprocess(img0):
    color_Low = np.array([0,0,200])
    color_High = np.array([50,50,255])
    img_dst = cv2.inRange(img0,color_Low,color_High)
    #tmp = str(time.time())+".png"
    #cv2.imwrite(tmp, img_dst)

    return img_dst.astype(int)


def calTemperature(img, curfacelum, list_templates):
    roiw = list_templates[0].shape[1] #16#17
    roih = list_templates[0].shape[0] #24#23
    roiimg0 = img[67:67+roih, 1175-640:1175-640+roiw]
    roiimg1 = img[67:67+roih, 1191-640:1191-640+roiw]
    roiimg2 = img[67:67+roih, 1222-640:1222-640+roiw]
    roiimg3 = img[387:387+roih, 1175-640:1175-640+roiw]
    roiimg4 = img[387:387+roih, 1191-640:1191-640+roiw]
    roiimg5 = img[387:387+roih, 1222-640:1222-640+roiw]

    max_pixlum_bgr = img[70, 1270-640]
    b = max_pixlum_bgr[0]
    g = max_pixlum_bgr[1]
    r = max_pixlum_bgr[2]
    max_pixlum = r * 0.299 + g * 0.587 + b * 0.114 #rectimg_max_pixlum_gray[0][0]

    min_pixlum_bgr = img[409, 1270-640]
    b = min_pixlum_bgr[0]
    g = min_pixlum_bgr[1]
    r = min_pixlum_bgr[2]
    min_pixlum = r * 0.299 + g * 0.587 + b * 0.114 #rectimg_min_pixlum_gray[0][0]

    template0 = preprocess(roiimg0)
    template1 = preprocess(roiimg1)
    template2 = preprocess(roiimg2)
    template3 = preprocess(roiimg3)
    template4 = preprocess(roiimg4)
    template5 = preprocess(roiimg5)
    #cv2.imwrite("uuuuu.jpg", template)

    num0= matchTemplates(template0, list_templates)
    num1= matchTemplates(template1, list_templates)
    num2= matchTemplates(template2, list_templates)
    num3= matchTemplates(template3, list_templates)
    num4= matchTemplates(template4, list_templates)
    num5= matchTemplates(template5, list_templates)

    # max temperature in current full ir img
    max_temperature = num0 * 10 + num1 + num2 * 0.1
    min_temperature = num3 * 10 + num4 + num5 * 0.1
    print("pppppppppppppppppppppppppppppppppppppppppppppppppppppmax: ", max_temperature)
    print("pppppppppppppppppppppppppppppppppppppppppppppppppppppmin: ", min_temperature)

    # calulate current face temperature
    rate = (curfacelum - min_pixlum) / (max_pixlum - min_pixlum)
    curfacetemperature = (max_temperature - min_temperature) * rate + min_temperature
    
    return curfacetemperature


def getTemperature(irimg_raw, list_face, posCalibM, list_templates, configParams):
    '''
    input: ir img, face bboxs
    output: every face's temperature
    '''
    irimgh = irimg_raw.shape[0]
    irimgw = irimg_raw.shape[1]

    errcode = 0
    list_temperatures = []
    facenum = len(list_face) # the number of faces in current img
    for i in range(facenum):
        facebbox = list_face[i]['bbox']
        xl = facebbox[0]
        yu = facebbox[1]
        xr = facebbox[2]
        yd = facebbox[3]

        # transform visiblelight face bbox to IR face bbox
        ps0 = np.array([xl, yu, 1])
        pd0 = np.dot(posCalibM, ps0)
        irxl = int(pd0[0])
        iryu = int(pd0[1])
        
        ps1 = np.array([xr, yd, 1])
        pd1 = np.dot(posCalibM, ps1)
        irxr = int(pd1[0])
        iryd = int(pd1[1])

        if irxl < 0:
            irxl = 0
        if irxr > 619: #irimgw - 1:  # temperture bar on right side may infact result
            irxr = 619 - 1 #irimgw - 1
        if irxr <= irxl:
           errcode = 1 

        if iryu < 0:
            iryu = 0
        if iryd > irimgh - 1:
            iryd = irimgh - 1
        if iryd <= iryu:
           errcode = 1

        if errcode == 0:
            try:
                irfacebboximg = irimg_raw[iryu:iryd, irxl:irxr]
                irfacebboximg = cv2.cvtColor(irfacebboximg, cv2.COLOR_BGR2GRAY)
                high = int(np.max(irfacebboximg))
                #low = int(np.min(irfacebboximg))
                #mid = int(high - (high - low)*0.1)
                #mask = cv2.inRange(irfacebboximg, mid, high)/255
                #num = np.sum(mask)
                #sum = np.sum(irfacebboximg * mask) 
                #if num:
                curfacelum = high #sum / num
                #    #curfacetemperature = temperatureCalib[0] * curfacetemperature + temperatureCalib[1]
                curfacetemperature = calTemperature(irimg_raw, curfacelum, list_templates)
                list_temperatures.append(int(curfacetemperature * 10))
                #else:
                #    curfacetemperature = -1
                #    list_temperatures.append(int(-1))
            except:
                curfacetemperature = -1
                list_temperatures.append(int(-1))                
        else:
            curfacetemperature = -1
            list_temperatures.append(int(-1))
        
        # draw
        if errcode == 0 and curfacetemperature > configParams.config_bodyTemperatureThreshold:#37.5:
            cv2.rectangle(irimg_raw, (irxl,iryu),(irxr,iryd),(0,0,255),3)
            cv2.putText(irimg_raw, str(int(10*curfacetemperature)/10), (irxl,iryu+20), cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.8, (0,0,255))
        elif errcode == 0 and curfacetemperature <= configParams.config_bodyTemperatureThreshold:#37.5:
            cv2.rectangle(irimg_raw, (irxl,iryu),(irxr,iryd),(0,255,0),3)
            cv2.putText(irimg_raw, str(int(10*curfacetemperature)/10), (irxl,iryu+20), cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.8, (0,0,255))

    # check if read temperature err
    isGetTemperatureErr = 0
    for temperature in list_temperatures:
        if temperature == -1:
            isGetTemperatureErr = 1

    return isGetTemperatureErr, list_temperatures


'''def prepareTemplates():
    for k in range(10):
        img0 = cv2.imread("./11111/"+str(k)+".jpg")
        print("type: ", type(img0))
        print("shape: ", img0.shape)
        print(img0[20][10])
        w = img0.shape[1]
        h = img0.shape[0]
        for i in range(h):
            for j in range(w):
                b = img0[i][j][0]
                g = img0[i][j][1]
                r = img0[i][j][2]
                btmp = 0
                gtmp = max(int(g)-int(b), 0)
                rtmp = max(int(r)-int(b), 0)
                if gtmp < 50:
                    gtmp = 0
                if rtmp < 50:
                    rtmp = 0
                if rtmp > 100:
                    btmp = 255
                    gtmp = 255
                    rtmp = 255
                img0[i][j][0] = btmp
                img0[i][j][1] = gtmp
                img0[i][j][2] = rtmp
        img0gray = cv2.cvtColor(img0,cv2.COLOR_BGR2GRAY)
        img0gray = cv2.resize(img0gray,(16,24))#(17,23))
        cv2.imwrite(str(k)+".jpg", img0gray)
        print(img0[20][10])'''


if __name__ == "__main__":

    #prepareTemplates()
  
    img = cv2.imread("./11111/frame11.jpg")
    roiw = 16#17
    roih = 24#23
    roiimg0 = img[67:67+roih, 1175:1175+roiw]
    roiimg1 = img[67:67+roih, 1191:1191+roiw]
    roiimg2 = img[67:67+roih, 1222:1222+roiw]
    roiimg3 = img[387:387+roih, 1175:1175+roiw]
    roiimg4 = img[387:387+roih, 1191:1191+roiw]
    roiimg5 = img[387:387+roih, 1222:1222+roiw]

    template = preprocess(roiimg0)
    result0 = matchTemplates(template)
    template = preprocess(roiimg1)
    result1 = matchTemplates(template)
    template = preprocess(roiimg2)
    result2 = matchTemplates(template)
    max = result0*10+result1+result2*0.1
    print("max is: ", max)
 
    template = preprocess(roiimg3)
    result0 = matchTemplates(template)
    template = preprocess(roiimg4)
    result1 = matchTemplates(template)
    template = preprocess(roiimg5)
    result2 = matchTemplates(template)
    min = result0*10+result1+result2*0.1
    print("min is: ", min)

